#include "message.h"
#include <errno.h>
#include <cstdlib>

MessageChannel::MessageChannel(key_t pKey) {
	int flag = IPC_CREAT | 0666;
	
	mId = msgget(pKey , flag);
	
	if (mId < 0) { ///failed
		isOpen = false;
	}
	else { ///success
		mKey = pKey;
		isOpen = true;
	}
}
	
MessageChannel::~MessageChannel() {}

int MessageChannel::receive(IMessage* pMessage, int pSize) {
	//cout << "RECEIVING" << endl;
	char* tBuff = new char[4 + pSize];
	
	int tResult = msgrcv(mId , tBuff , pSize , pMessage->getMessageType() , 0);
	
	if (tResult < 0) { ///Failed
		
	}
	else { ///success
		pMessage->setBuffer(tBuff , 4 + pSize);
	}
	
	delete [] tBuff;
	return tResult;
}

int MessageChannel::getId() {
	return mKey;
}

int MessageChannel::send(IMessage* pMessage) {
	int tResult = msgsnd(this->mId , pMessage->getBuffer() , pMessage->getLength() , IPC_NOWAIT);
	
	return tResult;
}
